package com.ruoyi.web.controller.common;

import com.ruoyi.common.core.domain.AjaxResult;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.nio.charset.StandardCharsets;

@Slf4j
@RestController
public class VideoController {

    @PostMapping("/video/test")
    public AjaxResult testVideo(@RequestBody String path){
        log.info("path is :{}", path);
        return AjaxResult.success("success");
    }

    @PostMapping(value = "/video/play-manual", produces = "video/mp4")
    public void playVideoManual(@RequestBody String videoPath, HttpServletResponse response) throws IOException {
        File videoFile = new File(videoPath);
        BufferedInputStream bis = null;
        OutputStream os = null;

        try {
            // 1. 验证文件
            if (!videoFile.exists() || !videoFile.isFile()) {
                response.setStatus(HttpStatus.NOT_FOUND.value());
                response.getWriter().write("文件不存在");
                return;
            }

            // 2. 配置响应头
            response.setContentType("video/mp4");
            response.setContentLengthLong(videoFile.length()); // 大文件支持（long 类型）
            response.setHeader("Content-Disposition", "inline; filename=" +
                    new String(videoFile.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));

            // 3. 手动流式输出（分块读取，避免内存溢出）
            bis = new BufferedInputStream(new FileInputStream(videoFile));
            os = response.getOutputStream();
            byte[] buffer = new byte[1024 * 1024]; // 1MB 缓冲区（根据服务器性能调整）
            int len;
            while ((len = bis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
                os.flush(); // 强制刷新缓冲区，避免数据堆积
            }

        } catch (IOException e) {
            try {
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                response.getWriter().write("视频播放失败");
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } finally {
            // 4. 关闭流（避免资源泄露）
            if (bis != null) bis.close();
            if (os != null) os.close();
        }
    }
}
